<?php
// 定义配置文件路径
$configPath = __DIR__ . '/config.php';

/**
 * 记录当天链接点击数
 * @param string $url 链接URL
 * @param string $title 链接标题
 */
function recordDailyClick($url, $title = '') {
    $clickStatsFile = __DIR__ . '/daily_clicks.json';
    $today = date('Y-m-d');
    $currentTime = date('Y-m-d H:i:s');
    
    // 获取现有统计数据
    $clickData = [];
    if (file_exists($clickStatsFile)) {
        $content = file_get_contents($clickStatsFile);
        $clickData = json_decode($content, true) ?? [];
    }
    
    // 初始化数据结构
    if (empty($clickData)) {
        $clickData = [
            'last_date' => $today,
            'today_clicks' => 0,
            'total_clicks' => 0,
            'today_links' => [],  // 当天各链接的点击记录
            'click_details' => []  // 详细的点击记录
        ];
    }
    
    // 检查是否跨天，如果跨天则归档旧数据并重置当天数据
    if (isset($clickData['last_date']) && $clickData['last_date'] !== $today) {
        // 归档前一天的数据到logs目录
        if (!empty($clickData['today_links'])) {
            archiveDailyClickData($clickData['last_date'], $clickData);
        }
        
        // 重置当天数据
        $clickData['last_date'] = $today;
        $clickData['today_clicks'] = 0;
        $clickData['today_links'] = [];
        $clickData['click_details'] = [];
    }
    
    // 确保today_links字段存在（兼容旧版本数据）
    if (!isset($clickData['today_links'])) {
        $clickData['today_links'] = [];
    }
    if (!isset($clickData['click_details'])) {
        $clickData['click_details'] = [];
    }
    
    // 更新总点击数
    $clickData['today_clicks']++;
    $clickData['total_clicks']++;
    
    // 记录具体链接的点击次数
    if (!isset($clickData['today_links'][$url])) {
        $clickData['today_links'][$url] = [
            'title' => $title,
            'url' => $url,
            'clicks' => 0,
            'first_click' => $currentTime
        ];
    }
    $clickData['today_links'][$url]['clicks']++;
    $clickData['today_links'][$url]['last_click'] = $currentTime;
    
    // 记录详细的点击记录（包含时间戳、IP等）
    $clickDetail = [
        'url' => $url,
        'title' => $title,
        'timestamp' => time(),
        'datetime' => $currentTime,
        'ip' => getVisitorIP(),
        'user_agent' => $_SERVER['HTTP_USER_AGENT'] ?? '',
        'referer' => $_SERVER['HTTP_REFERER'] ?? ''
    ];
    $clickData['click_details'][] = $clickDetail;
    
    // 限制click_details数组大小，只保留最近1000条
    if (count($clickData['click_details']) > 1000) {
        $clickData['click_details'] = array_slice($clickData['click_details'], -1000);
    }
    
    // 写入文件
    file_put_contents($clickStatsFile, json_encode($clickData, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));
}

/**
 * 归档每日点击数据到logs目录
 * @param string $date 日期
 * @param array $data 数据
 */
function archiveDailyClickData($date, $data) {
    $logsDir = __DIR__ . '/logs/clicks';
    if (!is_dir($logsDir)) {
        mkdir($logsDir, 0755, true);
    }
    
    $archiveFile = $logsDir . '/clicks_' . $date . '.json';
    $archiveData = [
        'date' => $date,
        'total_clicks' => $data['today_clicks'] ?? 0,
        'links' => $data['today_links'] ?? [],
        'details' => $data['click_details'] ?? [],
        'archived_at' => date('Y-m-d H:i:s')
    ];
    
    file_put_contents($archiveFile, json_encode($archiveData, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));
}

/**
 * 获取访问者IP地址
 * @return string
 */
function getVisitorIP() {
    $ip = '';
    if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
    } elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
        $ip = $_SERVER['HTTP_CLIENT_IP'];
    } elseif (isset($_SERVER['HTTP_X_REAL_IP'])) {
        $ip = $_SERVER['HTTP_X_REAL_IP'];
    } else {
        $ip = $_SERVER['REMOTE_ADDR'] ?? '';
    }
    // 如果有多个IP，取第一个
    if (strpos($ip, ',') !== false) {
        $ip = trim(explode(',', $ip)[0]);
    }
    return $ip;
}

// 获取并解码目标URL参数
$targetUrl = urldecode($_GET['url'] ?? '');

// 如果目标URL为空，则输出错误信息并终止脚本
if (empty($targetUrl)) {
    die('参数错误：未提供URL。');
}

// 检查配置文件是否存在且可读
if (!file_exists($configPath) || !is_readable($configPath)) {
    die('配置文件丢失或不可读。');
}

// 引入配置文件，这将使得 $conf 和 $Data 变量在当前作用域可用
include $configPath;

// 确保 $Data 是一个数组，如果配置文件格式不正确或 $Data 未定义，则进行处理
if (!isset($Data) || !is_array($Data)) {
    // 如果$Data无效，我们直接跳转到首页
    echo '<!DOCTYPE html><html><head><meta http-equiv="refresh" content="0;url=index.php"></head><body>配置错误，正在返回首页...</body></html>';
    exit;
}

$found = false; // 标记是否找到匹配的链接
$linkTitle = ''; // 保存链接标题
// 遍历链接数据以查找匹配项并更新点击次数
foreach ($Data as &$link) { // 注意使用引用 &$link 以便直接修改数组元素
    if (isset($link['url']) && $link['url'] === $targetUrl) {
        $link['clicks'] = ($link['clicks'] ?? 0) + 1; // 增加点击次数，如果 'clicks' 不存在则默认为0
        $linkTitle = $link['title'] ?? ''; // 保存链接标题
        $found = true;
        break; // 找到匹配项后即可退出循环
    }
}

// 如果找到了链接并更新了点击次数，则将更改写回配置文件
if ($found) {
    // 记录当天链接点击数到统计文件（传入URL和标题）
    recordDailyClick($targetUrl, $linkTitle);
    
    // 重新构建要写入文件的PHP代码字符串
    // 确保 $conf 变量也存在，如果不存在，则创建一个空的，以防原始 config.php 中没有 $conf
    $confToWrite = isset($conf) && is_array($conf) ? $conf : [];

    $phpCode = "<?php\n\n";
    // 使用短数组语法 [] 输出 $conf
    $phpCode .= "\$conf = " . preg_replace(['/^array \(/', '/\)$/'], ['[', ']'], var_export($confToWrite, true)) . ";\n\n";
    // 使用短数组语法 [] 输出 $Data，并确保内部数组也是短语法且无数字索引
    $dataExport = var_export($Data, true);
    $dataExport = preg_replace('/^array \(/', '[', $dataExport);
    $dataExport = preg_replace('/\)$/', ']', $dataExport);
    $dataExport = preg_replace('/\s*\d+\s*=>\s*array\s*\(/', '[', $dataExport);
    $dataExport = preg_replace('/array\s*\(/', '[', $dataExport);
    $dataExport = preg_replace('/\)/', ']', $dataExport);
    $phpCode .= "\$Data = " . $dataExport . ";\n";

    // 尝试写入更新后的配置到文件
    if (file_put_contents($configPath, $phpCode) === false) {
        // 如果写入失败，可以记录错误或通知管理员，但仍然尝试跳转
        // error_log('无法更新配置文件：' . $configPath);
    }

    // 输出HTML跳转页面（立即跳转）
    echo '<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta http-equiv="refresh" content="0;url=' . htmlspecialchars($targetUrl) . '">
    <title>正在跳转 - 导航网</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body { 
            font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
            position: relative;
            overflow: hidden;
        }
        
        /* 背景动画粒子 */
        .bg-animation {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            overflow: hidden;
            z-index: 1;
        }
        
        .particle {
            position: absolute;
            background: rgba(255, 255, 255, 0.1);
            border-radius: 50%;
            animation: float 6s ease-in-out infinite;
        }
        
        @keyframes float {
            0%, 100% { transform: translateY(0px) rotate(0deg); }
            50% { transform: translateY(-20px) rotate(180deg); }
        }
        
        .container { 
            background: rgba(255, 255, 255, 0.95);
            backdrop-filter: blur(10px);
            padding: 40px;
            border-radius: 20px;
            box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
            text-align: center;
            max-width: 500px;
            width: 90%;
            position: relative;
            z-index: 10;
            animation: slideIn 0.6s ease-out;
        }
        
        @keyframes slideIn {
            from {
                opacity: 0;
                transform: translateY(30px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }
        
        .icon {
            width: 60px;
            height: 60px;
            margin: 0 auto 20px;
            background: linear-gradient(135deg, #667eea, #764ba2);
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            animation: pulse 2s ease-in-out infinite;
        }
        
        @keyframes pulse {
            0%, 100% { transform: scale(1); }
            50% { transform: scale(1.1); }
        }
        
        .icon::before {
            content: "→";
            color: white;
            font-size: 24px;
            font-weight: bold;
        }
        
        .loading { 
            font-size: 24px;
            color: #333;
            margin-bottom: 15px;
            font-weight: 600;
        }
        
        .countdown {
            font-size: 18px;
            color: #667eea;
            margin: 20px 0;
            font-weight: 500;
            padding: 10px 20px;
            background: rgba(102, 126, 234, 0.1);
            border-radius: 25px;
            display: inline-block;
        }
        
        .url-container {
            margin: 25px 0;
            padding: 15px;
            background: #f8f9fa;
            border-radius: 10px;
            border-left: 4px solid #667eea;
        }
        
        .url-label {
            font-size: 12px;
            color: #666;
            margin-bottom: 5px;
            text-transform: uppercase;
            letter-spacing: 1px;
        }
        
        .url { 
            color: #333;
            font-size: 14px;
            word-break: break-all;
            font-family: "Courier New", monospace;
        }
        
        .manual-link {
            margin-top: 20px;
            padding: 12px 24px;
            background: linear-gradient(135deg, #667eea, #764ba2);
            color: white;
            text-decoration: none;
            border-radius: 25px;
            display: inline-block;
            transition: all 0.3s ease;
            font-weight: 500;
        }
        
        .manual-link:hover {
            transform: translateY(-2px);
            box-shadow: 0 10px 20px rgba(102, 126, 234, 0.3);
            text-decoration: none;
            color: white;
        }
        
        .progress-bar {
            width: 100%;
            height: 4px;
            background: #e9ecef;
            border-radius: 2px;
            margin: 20px 0;
            overflow: hidden;
        }
        
        .progress-fill {
            height: 100%;
            background: linear-gradient(90deg, #667eea, #764ba2);
            border-radius: 2px;
            animation: progress 0.3s linear;
        }
        
        @keyframes progress {
            from { width: 0%; }
            to { width: 100%; }
        }
        
        @media (max-width: 480px) {
            .container {
                padding: 30px 20px;
                margin: 20px;
            }
            
            .loading {
                font-size: 20px;
            }
            
            .countdown {
                font-size: 16px;
            }
        }
    </style>
</head>
<body>
    <div class="bg-animation" id="bgAnimation"></div>
    
    <div class="container">
        <div class="icon"></div>
        <div class="loading">正在为您跳转</div>
        <div class="countdown" id="countdown">正在跳转...</div>
        
        <div class="progress-bar">
            <div class="progress-fill"></div>
        </div>
        
        <div class="url-container">
            <div class="url-label">目标地址</div>
            <div class="url">' . htmlspecialchars($targetUrl) . '</div>
        </div>
        
        <a href="' . htmlspecialchars($targetUrl) . '" class="manual-link">立即跳转</a>
    </div>
    
    <script>
        // 创建背景动画粒子
        function createParticles() {
            const bgAnimation = document.getElementById("bgAnimation");
            for (let i = 0; i < 20; i++) {
                const particle = document.createElement("div");
                particle.className = "particle";
                particle.style.left = Math.random() * 100 + "%";
                particle.style.top = Math.random() * 100 + "%";
                particle.style.width = (Math.random() * 10 + 5) + "px";
                particle.style.height = particle.style.width;
                particle.style.animationDelay = Math.random() * 6 + "s";
                bgAnimation.appendChild(particle);
            }
        }
        
        // 立即跳转
        window.location.href = "' . addslashes($targetUrl) . '";
        
        // 初始化背景动画（虽然可能看不到，但保持页面完整性）
        createParticles();
    </script>
</body>
</html>';
    exit;
}

// 如果循环完毕仍未找到匹配的链接，则跳转回首页
echo '<!DOCTYPE html><html><head><meta http-equiv="refresh" content="0;url=index.php"></head><body>链接未找到，正在返回首页...</body></html>';
exit;
